package com.newtouch.cq.base.starter.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.io.File;
import java.util.List;
import java.util.Scanner;

/**
 * @author Alex
 * @Description 代码生产器
 * @time 2021年07月27日 15:35:00
 */
public class GeneratorCodeUtil {

    public static void main(String[] args) {

        String moduleName = "cq-newtouch";

        String dbUrl = "jdbc:mysql://49.4.67.31:33101/adp_dev?serverTimezone=UTC";

        String username = "adp_p";

        String pwd = "1hb6sqt@NT";

        String parentPackage = "com.newtouch.cq.base.starter.business";

        String author = "Alex";

        String[] tables = ArrayUtil.toArray(CollUtil.newArrayList("sys_log"),String.class);

        generatorByDb(moduleName, dbUrl, username, pwd, parentPackage, author, tables);
    }

    private static void generatorByDb(String moduleName, String dbUrl, String username, String pwd, String parentPackage, String author, String[] tables) {
        DataSourceConfig dsc = new DataSourceConfig
                .Builder(dbUrl, username, pwd)
                .build();
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator(dsc);


        String projectPath = System.getProperty("user.dir");

        // 全局配置
        GlobalConfig globalConfig = new GlobalConfig
                .Builder()
                .outputDir(projectPath + "/" + moduleName + "/src/main/java")
                .author(author)
                .openDir(false).enableSwagger()
                .build();

        // 包配置
        PackageConfig packageConfig = new PackageConfig
                .Builder()
                .parent(parentPackage)
//                .moduleName(moduleName)
//                .mapper("dao")
                .xml("xml")
                .build();

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig
                .Builder()
//                .mapperXml(null)
                .build();

        // 策略配置
        StrategyConfig strategyConfig = new StrategyConfig
                .Builder()
                .addInclude(tables)
                .entityBuilder().naming(NamingStrategy.underline_to_camel).enableLombok()
                .mapperBuilder().enableBaseResultMap()
                .controllerBuilder().enableRestStyle().enableHyphenStyle()
                .build();


        mpg.global(globalConfig);
        mpg.packageInfo(packageConfig);
        mpg.template(templateConfig);
        mpg.strategy(strategyConfig);

        ConfigBuilder configBuilder = new ConfigBuilder(mpg.getPackageInfo(), mpg.getDataSource(), mpg.getStrategy(), mpg.getTemplate(), mpg.getGlobalConfig(), mpg.getInjectionConfig());
        configBuilder.getPathInfo().put("xml_path",joinPath(System.getProperty("user.dir")+ File.separator+moduleName+File.separator+"src\\main\\resources","mapper"));

        mpg.config(configBuilder);
        mpg.execute(new FreemarkerTemplateEngine());

        formatMapping(configBuilder);
    }

    private static void formatMapping(ConfigBuilder configBuilder) {
       configBuilder.getTableInfoList().stream().forEach(tableInfo -> {
           String entityName = tableInfo.getEntityName();
           String controllerFile = String.format(configBuilder.getPathInfo().get("controller_path") + File.separator + tableInfo.getControllerName() + ".java", entityName);
           System.out.println(controllerFile);
           List<String> strs = FileUtil.readLines(controllerFile, CharsetUtil.CHARSET_UTF_8);
           int i =0;
           for(String s:strs) {
               if (StrUtil.contains(s, "RequestMapping") && StrUtil.contains(s, "-")) {
                   CollUtil.setOrAppend(strs,i,StrUtil.replace(s, "-", "/"));
                   break;
               }
               i++;
           }
           FileUtil.writeLines(strs,controllerFile,CharsetUtil.CHARSET_UTF_8);
       });

    }


    private static String joinPath(String parentDir, String packageName) {
        if (StringUtils.isBlank(parentDir)) {
            parentDir = System.getProperty("java.io.tmpdir");
        }

        if (!StringUtils.endsWith(parentDir, File.separator)) {
            parentDir = parentDir + File.separator;
        }

        packageName = packageName.replaceAll("\\.", "\\" + File.separator);
        return parentDir + packageName;
    }

    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help);
        if (scanner.hasNext()) {
            String ipt = scanner.nextLine();
            if (StrUtil.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }


}
